package com.atguigu.gmall.pay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.enums.OrderStatus;
import com.atguigu.gmall.enums.ProcessStatus;
import com.atguigu.gmall.feign.order.OrderFeignClient;
import com.atguigu.gmall.order.entity.OrderInfo;
import com.atguigu.gmall.pay.properties.AlipayProperties;
import com.atguigu.gmall.pay.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 面试题：前台接口的开放和后台接口开发有什么区别？
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderFeignClient orderFeignClient ;

    @Autowired
    private AlipayProperties alipayProperties ;

    @Autowired
    private AlipayClient alipayClient ;

    @Override
    public String pay(String orderId) {

        // 远程调用service-order微服务的接口，根据订单的id查询订单数据
        Result<OrderInfo> orderInfoResult = orderFeignClient.findByOrderId(orderId);
        OrderInfo orderInfo = orderInfoResult.getData();
        if(OrderStatus.CLOSED.name().equals(orderInfo.getOrderStatus()) && ProcessStatus.CLOSED.name().equals(orderInfo.getProcessStatus())) {
            throw new GmallException(ResultCodeEnum.ORDER_PAY_ERROR) ;
        }

        // 创建aAlipayRequest对象封装请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(alipayProperties.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayProperties.getNotifyUrl());

        // 构建一个业务的json数据
        Map<String , Object> map = new HashMap<>() ;
        map.put("out_trade_no" , orderInfo.getOutTradeNo()) ;
        map.put("total_amount" , orderInfo.getTotalAmount()) ;
        map.put("subject" , orderInfo.getTradeBody()) ;
        map.put("product_code" , "FAST_INSTANT_TRADE_PAY") ;
        long timeExpire = System.currentTimeMillis() + 1000 * 60 * 3 ;
        Date date = new Date(timeExpire);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
        String format = simpleDateFormat.format(date);
        map.put("time_expire" , format) ;
        alipayRequest.setBizContent(JSON.toJSONString(map)) ;

        try {

            // 发送请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
            return result ;

        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return null;
    }

}
